/**
 * Created by yunpeng on 2014/12/4.
 */
/*bcrypt = require('bcrypt'),
    SALT_WORK_FACTOR = 10;*/
//var db = require('../utils/dbConn');

var UserDao = require('../utils/commonDBConn').Table;

var debug = require('debug')('UserModel');

var Users = function(username, nickname, password, usertype, integral, active_id, did, createtime) {
    this.username = username;
    this.nickname = nickname;
    this.password = password;
    this.usertype = usertype;
    this.integral = integral;
    this.active_id = active_id;
    this.did = did;
    this.createtime = createtime;
    if (typeof this.list != 'function') {//仅在第一次调用的初始化
        /*Users.prototype.save = function(){
            var sql = 'insert into users set ?';
            //var args = {username:this.username,nickname:this.nickname,password:this.password,usertype:this.usertype,integral:this.integral,active_id:this.active_id,did:this.did,createtime:this.createtime};
            db.execQuery(sql,this,function(result){
                console.log(result);
            });
        };*/

        Users.prototype.list = function(option, callback){
            debug('执行查询');
            var dao = new UserDao('users');
            var countSql = 'select count(*) total ';
            var dataSql = 'select id,nickname,username,phone,email,img,usertype,integral,modelnum,carnum,insuranceDate,u.createtime createtime,lname,u.lid lid ';
            var sql = ' from users u LEFT JOIN life_service l on u.lid=l.lid where true ';
            var args = [];
            if(option.toDate){
                sql += ' and u.createtime<=?';
                args.push(option.toDate);
            }
            if(option.fromDate){
                sql += ' and u.createtime>=?';
                args.push(option.fromDate);
            }

            if(option.searchName){
                sql += ' and username like?';
                args.push('%'+option.searchName+'%');
            }
            if(option.userType){
                sql += ' and usertype=?';
                args.push(option.userType);
            }

            sql += ' order by u.'+ option.sort + ' ' + option.order;

            dao.executeSql(countSql + sql, args, function(err, count){
                if(!option.page){
                    option.page = 1;
                    option.rows = 10;
                }
                sql += ' limit ?,?';
                args.push( (option.page-1)*option.rows, option.rows);
                dao.executeSql(dataSql + sql, args, function(err, resultSet){
                    callback({
                        total:count[0].total,
                        rows:resultSet
                    });
                })
            })

            /* if(!option.toDate){option.toDate = this.toMysqlDate(new Date());}
             if(!option.fromDate){option.fromDate = '2010-1-1';}
             var sql = "select * from users where createtime>'"+option.fromDate+"' and createtime<='"+option.toDate+"'";
             if(option.searchName){
             sql += " and username like '" + option.searchName + "'";
             }
             sql += " order by createtime "+option.order+" limit "+((option.page-1)*option.rows)+","+option.rows;
             //var sql = 'select * from users';
             db.execQuery(sql, null, function(resultSet){
             db.execQuery('select count(*) total from users',null,function(count){
             callback({
             total:count[0].total,
             rows:resultSet
             });
             })

             });*/
        }

        Users.prototype.saveUpdate = function(user, callback){
            debug('增加、修改一条用户信息');
            user.usertype = Number(user.usertype);
            user.integral = Number(user.integral);
            var sql = '';
            var condition = {};
            var handler = function(err, result){
                var rs = {state:'fail'};
                if(!err && result.affectedRows == 1){rs.state = 'success';}
                callback(rs);
            }
            var dao = new UserDao('users');
            if(user.id){
                user.id = Number(user.id);
                dao.update('id', user, handler);
            }else{
                delete user.id;
                dao.insert(user, handler);
            }
            /*if(user.id){
             condition = [user, user.id];
             sql = "update users set ?? where id=?";
             }else{
             condition = user;
             sql = "insert into users set ?";
             }
             db.execQuery(sql, condition, handler);*/
        }

        Users.prototype.delete = function(idSet, callback){
            var dao = new UserDao('users');
            dao.delete('id', idSet, function(err, result){
                var rs = {state:'fail'};
                if(!err && result.affectedRows!=0){
                    rs.state = 'success';
                }else if(err){
                    debug(err);
                };
                callback(rs);
            })
        }

        Users.prototype.toMysqlDate = function(date){
            var str = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate() + ' '  + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
            return str;

        }

        Users.prototype.signActivity = function(option, callback){
            var insertSql, insertArgs, updateSql, updateArgs;
            var aid, tName, aName;
            var count = 'currenttotal';
            var value = {};
            option.userid = Number(option.userid);
            option.aid = Number(option.aid);
            value.userid = option.userid;
            switch(option.aType){
                case '3':value.aid=option.aid;tName = 'user_activity';
                    aid = 'aid';aName = 'activity';
                    break;
                case '2':value.did=option.aid; tName = 'user_seldrive';
                    aid = 'did';aName = 'selfdriving'; count = 'count'; break;
                case '4':value.vid=option.aid; tName = 'user_voice';
                    aid = 'vid';aName = 'voice'; break;
            }
            value.datejoined = new Date();
            insertSql = "insert into ?? set ?";
            insertArgs = [tName, value];
            updateSql = "update ?? set ??=(select count(*) from ?? where ??=?) where ??=?";
            updateArgs = [aName, count, tName, aid, option.aid, 'id', option.aid];
            var dao = new UserDao();
            dao.getConnection(function(conn){
                var q1 = conn.query(insertSql, insertArgs, function(err, data){
                    debug('sign--'+q1.sql);
                    if(!err){
                        var q2 = conn.query(updateSql, updateArgs, function(err, data){
                            debug('update--'+q2.sql);
                            conn.release();
                        })
                        callback('true');
                    }else{
                        callback('false');
                    }
                })
            })
        }

        Users.prototype.checkActivity = function(option, callback){
            if(!option.uid || !option.aid || !option.aname){
                return;
            }
            var tName;
            var condition = '';
            switch(option.aname){
                case 'activity':condition += ' and aid=';tName = 'user_activity';break;
                case 'drive':condition += ' and did='; tName = 'user_seldrive'; break;
                case 'voice':condition += ' and vid='; tName = 'user_voice'; break;
            }
            condition += option.aid + ' and userid=' + option.uid;
            var dao = new UserDao(tName);
            dao.count(condition, function(err, result){
                debug('checkActivity---'+result);
                callback(result);
            })
        }

        Users.prototype.myActivity = function(option, callback){
            //var param = [option.userid, option.page, option.rows];
            var aName,mName,aid;
            switch (option.aname){
                case 'activity':
                    aName = 'activity';
                    mName = 'user_activity';
                    aid = 'aid';
                    break;
                case 'drive':
                    aName = 'selfdriving';
                    mName = 'user_seldrive';
                    aid = 'did';
                    break;
                case 'voice':
                    aName = 'voice';
                    mName = 'user_voice';
                    aid = 'vid';
                    break;
            }
            var sql = 'select * from ?? act,?? my where userid=? and my.??=act.id '
                +'order by my.datejoined desc limit ?,?';
            option.userid = Number(option.userid);
            option.rows = Number(option.rows);
            option.page = Number(option.page);
            var param = [aName, mName, option.userid, aid];
            param.push((option.page-1)*option.rows);
            param.push(option.rows);
            var dao = new UserDao();
            dao.getConnection(function(conn){
                var query = conn.query(sql, param, function(err, data){
                    var result = {
                        rows:[],
                        total:0
                    }
                    if(err){

                    }else{
                        formatResultDate(data);
                        for(var i=0; i<data.length; i++){
                            data[i].aname = option.aname;
                        }
                        result.rows = data;
                    }
                    callback(result);
                    debug(query.sql);
                    conn.release();
                })
            })
        }

        Users.prototype.postComment = function(option, callback){
            if(option.aname=='drive'){
                option.aname='sd';
            }
            var dao = new UserDao(option.aname + 'comments');
            option[option.aname+'id'] = Number(option.aid);
            delete option.aname;
            delete option.aid;
            option.userid = Number(option.userid);
            if(!option.createtime){
                option.createtime = new Date();
            }
            dao.insert(option, function(err, data){
                if(!err){
                    callback(''+data.affectedRows);
                }else{
                    debug('post comment err---'+err);
                }
            })
        }
        Users.prototype.listComment = function(option ,callback){
            var columnStr = ' userid,content,c.createtime createtime,img,phone,username ';

            var aname = option.aname;
            if(aname == 'drive'){
                aname = 'sd';
            }
            var tableStr = ' '+aname+'comments c,users u ';

            var paramStr = ' where '+aname+'id=' + option.aid + ' and userid=u.id ';
            var pageStr = '';
            if(option.page){//分页查询
                var page = Number(option.page);
                var rows = Number(option.rows);
                pageStr += ' limit ' + (page-1)*rows +',' + rows;
            }
            /*var aid = option.aid;
             delete option.aname;
             delete option.aid;
             switch(aname){
             case 'activity':option.activityid = aid;break;
             case 'sd':option.sdid = aid;break;
             case 'voice':option.voiceid = aid;break;
             }*/
            var sql = 'select '+columnStr+' from '+ tableStr + paramStr + ' order by c.createtime desc' + pageStr;
            var countSql = 'select count(*) count from ' + aname + 'comments where '+ aname + 'id=' + option.aid;
            var result = {
                total:0,
                rows:[]
            }
            var dao = new UserDao();
            dao.getConnection(function( conn){
                conn.query(countSql, function(err, data){
                    if(!err ){//如果查询总条数，数据库无错
                        result.total = data[0].count;
                        if(result.total){//如果评论总条数不为0
                            var query = conn.query(sql, function(err, data){
                                if(!err){//如果查询评论，没有数据库错误
                                    formatResultDate(data);
                                    result.rows = data;
                                    callback(result);
                                }else{
                                    debug(err);
                                }
                                debug(query.sql);
                                conn.release();
                            })
                        }else{
                            conn.release();
                            callback(result);
                        }
                    }else{
                        debug('查询总评论条数，数据库错误' + err);
                        callback(result);
                    }
                })
            })
        }

        Users.prototype.modifyPwd = function(option, callback){
            if(typeof callback != 'function'){callback = function(){}}
            var sql = 'update users set password=? where id=? and password=?';
            var value = [
                option.newPwd,
                Number(option.userId),
                option.oldPwd
            ]
            var dao = new UserDao();
            dao.executeSql(sql, value, function(err, data){
                var result = {status:'1'};
                if(!err  && data.affectedRows == 1){
                    callback(result);
                }else{
                    result.status = '-1';
                    callback(result);
                }
            })
        }
        Users.prototype.bizModify = function(option, callback){
            if(typeof callback != 'function'){callback = function(){}}
            var sql = 'update users set ? where id=?';
            var value = [
                option,
                option.id
            ]
            var dao = new UserDao();
            dao.executeSql(sql, value, function(err, data){
                var result = {status:'1'};
                if(!err  && data.affectedRows == 1){
                    callback(result);
                }else{
                    result.status = '-1';
                    callback(result);
                }
            })
        }


        Users.prototype.updateImg = function(userid,img,callback){
            new UserDao('users').executeSql('UPDATE users SET  img = ? WHERE id = ?',[img,userid],function(err,result){
                if(err){
                    callback('false');
                }else{
                    callback('true');
                }
            });
        }


    }
}
function formatResultDate(result){
    var i, j, r;
    for(i=0; i<result.length; i++){
        r = result[i];
        for(j in r){
            if(r[j] instanceof Date){
                r[j] = localeDateTime(r[j]);
            }
        }
    }
    return result;
}
function localeDateTime(date){
    return date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+' '+date.toLocaleTimeString();
}
exports.Users = Users;